package com.example.app11_gridview.adapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.app11_gridview.R;

import java.util.List;

public class MainAdapter extends BaseAdapter {

    private Context context;

    private List<AppInfo> data;

    public MainAdapter(Context context, List<AppInfo> data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.isEmpty() ? 0 : data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.isEmpty() ? new AppInfo() : data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.item_main, null);
        }

        AppInfo appInfo = data.get(position);
        ImageView ivItemMainIcon = convertView.findViewById(R.id.iv_item_main_icon);
        ivItemMainIcon.setImageResource(appInfo.getIcon());

        TextView tvItemMainName = convertView.findViewById(R.id.tv_item_main_name);
        tvItemMainName.setText(appInfo.getName());

        // 如果sp中保存了数据，就就读取
        if(position == 0) {
            SharedPreferences sp = context.getSharedPreferences("app", Context.MODE_PRIVATE);
            String appName = sp.getString("appName", "手机防盗");
            tvItemMainName.setText(appName);
        }

        return convertView;
    }
}
